package com.wealth.pay.web.controller;

import iaas.annotation.Login;
import iaas.utils.CommonUtil;
import iaas.utils.ResultObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.wealth.commodity.service.IGoodsService;
import com.wealth.commodity.service.IPurrestrictionsService;
import com.wealth.member.entity.Membership;
import com.wealth.member.service.IMembershipService;
import com.wealth.order.entity.OrderPlat;
import com.wealth.order.service.IOrderPlatService;
import com.wealth.payment.entity.PaymentAccount;
import com.wealth.payment.enums.PaymentTypeEnum;
import com.wealth.payment.service.IPaymentAccountService;
import com.wealth.platform.entity.SldConfig;
import com.wealth.platform.enums.SldConfigTypeEnum;
import com.wealth.platform.service.ISldConfigService;
import com.wealth.system.web.controller.BaseController;
import com.wealth.wechat.entity.WechatConfig;
import com.wealth.wechat.service.WechatConfigService;
import com.wealth.wechat.service.WechatPayService;
import com.wealth.wechat.util.XmlParser;


/** 2015-5-26 add by wayne
 *  微信支付  回调处理接口 
 **/
@Controller
@RequestMapping("/pay")
public class PayController extends BaseController{
	
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private WechatPayService wechatPayService;
	@Autowired
	private WechatConfigService wechatConfigService;
	@Autowired
	private ISldConfigService sldConfigService;
	@Autowired
	private IPaymentAccountService accountService;
	@Autowired
	private IOrderPlatService orderPlatService;
	@Autowired
	private IMembershipService membershipService;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private IPurrestrictionsService purrestrictionsService;
	/** 
	 * 支付页面
	 */
	@RequestMapping(value="/{orderid}")
	@Login
	public String payForm(Model model,@PathVariable Long orderid)throws Exception{
		//会员身份
		//TODO query
		//TODO not exist then
		Membership membership = membershipService.getMemberShipByMemberIdAndCorpId(memberid, corpid);
		model.addAttribute("membership", membership);
				
		//企业微信信息
		//TODO not exist then
		WechatConfig config = wechatConfigService.getWechatConfigByCorpid(corpid);
		model.addAttribute("config", config);
		
		//订单信息
		//TODO not exist then or order status 
		OrderPlat orderPlat = orderPlatService.get(orderid) ;
		model.addAttribute("orderPlat", orderPlat);
		
		return "pay/wechatPay";
	}
	
	/** 统一支付接口 */
	@SuppressWarnings("finally")
	@RequestMapping(value="/wxgopay/{orderid}")
	@ResponseBody
	public ResultObject wxgopay(@PathVariable Long orderid,
			HttpServletRequest request,
			HttpSession session) {

		ResultObject rs = new ResultObject();
		try {		
			//企业微信信息
			WechatConfig config = wechatConfigService.getWechatConfigByCorpid(corpid);
			//二级域名
			SldConfig sldConfig = sldConfigService.getSldConfigByCorpIdAndType(corpid,SldConfigTypeEnum.WECHAT.getValue());
			//微信号
			String openid = request.getParameter("openid");
			//订单
			OrderPlat orderPlat = orderPlatService.get(orderid);
			//获取商家账号信息
			PaymentAccount payaccount = accountService.findByCorpIdAndPaymode(corpid, PaymentTypeEnum.WECHAT.getValue());
			//获取支付参数
			JSONObject result = wechatPayService.getPayParam(config, sldConfig, payaccount, orderPlat, openid, request);
			rs.setCode(result.get("errcode").toString());
			rs.setMsg(result.get("return_msg").toString());
			rs.setResult(result);
			
			//判断库存
			/*boolean isOk = orderPlatService.checkInventory(orderPlat);
			if(!isOk){
				rs.setCode("999");
				rs.setMsg("库存不足");
			}*/
			//判断商品是否已经下架
			boolean isDown=goodsService.checkIsDown(orderPlat);
			System.out.println(isDown+"  //判断商品是否已经下架");
			if(!isDown){
				rs.setCode("999");
				rs.setMsg("商品已经下架");
				return rs;
			}
			//判断商品是否超过限额
			boolean isPur=goodsService.checkPurRestrictions(orderPlat);
			if(!isPur){
				rs.setCode("999");
				rs.setMsg("超过商品的购买限额");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("支付接口错误");
		}finally{		
			System.out.println("result="+rs.getResult());
			return rs;
		}
	}
	
	/** 
	 * 支付异步通知
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value="/notify_url/{corpid}/{orderid}",method=RequestMethod.POST)
	public void wxpaytoNotify(ModelMap model,
			@PathVariable java.lang.Long corpid,
			@PathVariable java.lang.Long orderid,
			HttpServletRequest request,
			HttpServletResponse response)throws Exception
	{
		//wx支付结果通用通知
		System.out.println("=============================wx支付结果通用通知:..."+new Date());
	   	
	   	String notify_Xml = "<xml>"+
		"<return_code><![CDATA[%1$s]]></return_code>"+
		"<return_msg><![CDATA[%2$s]]></return_msg>"+
		"</xml>";
		   	
	   	String postStr = wechatPayService.readStreamParameter(request.getInputStream());
	   	System.out.println("====wx支付结果通用通知参数postStr=:"+postStr);
	   	if(CommonUtil.isNotNull(postStr)){
		   	Map<String, Object> map_result = new HashMap<String, Object>();
		   	map_result=XmlParser.xmlStr2Map(postStr);
		   	
		   	if(CommonUtil.isNotNull(map_result.get("return_code"))){
			    String return_code = map_result.get("return_code").toString();
			    //String return_msg = map_result.get("return_msg").toString();
				
			    OrderPlat orderPlat = orderPlatService.get(orderid);
				if(return_code.equals("SUCCESS")){
					//wx支付 服务器回调 服务器订单 查询
					if(null!=orderPlat){
						//支付成功
						orderPlatService.payOrder(orderPlat);
						
					}
				}else{
					//wx支付 服务器回调 服务器订单 查询
					if(null!=orderPlat){
						//支付失败
						//order.setPaystatus(PayStatusEnum.FAIL.getValue());
						//orderService.saveAdoptionOrder(order);
					}
				}
		   	}
	   	}
//	   	return notify_Xml.format(notify_Xml, "SUCCESS","OK");
	   	
	   	System.out.println("=============================wx支付结果通用通知完成:..."+notify_Xml.format(notify_Xml, "SUCCESS","OK"));
	   	wechatPayService.sendStream(response, notify_Xml.format(notify_Xml, "SUCCESS","OK"));
	}
}
